package com.buli.blmall.admin.system.service;

import cn.hutool.core.collection.CollectionUtil;
import com.buli.blmall.admin.system.entity.*;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 权限服务
 * @author xiang.gao
 * @date 2025/2/27 16:30
 */
@Service
@AllArgsConstructor
public class SysPermissionService {

    private final SysUserRoleService sysUserRoleService;
    private final SysRoleMenuService sysRoleMenuService;
    private final SysMenuService sysMenuService;
    private final SysRoleService sysRoleService;

    /**
     * 获取用户的菜单权限
     * @param sysUser
     * @return
     */
    public Set<String> gePermission(SysUser sysUser) {
        List<SysUserRole> userRoles = sysUserRoleService.getListByUserId(sysUser.getId());
        if(CollectionUtil.isEmpty(userRoles)) {
            return Collections.EMPTY_SET;
        }
        List<Long> roleIds = userRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
        List<SysRoleMenu> sysRoleMenuList = sysRoleMenuService.getListByRoleIds(roleIds);
        if (CollectionUtil.isEmpty(sysRoleMenuList)) {
            return Collections.EMPTY_SET;
        }
        List<Long> menuIds = sysRoleMenuList.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(menuIds)) {
            return Collections.EMPTY_SET;
        }
        List<SysMenu> listByIds = sysMenuService.getListByIds(menuIds);
        return listByIds.stream().map(SysMenu::getPerms).collect(Collectors.toSet());
    }

    /**
     * 获取用户的角色
     * @param sysUser
     * @return
     */
    public Set<String> getUserRoles(SysUser sysUser) {
        List<SysUserRole> userRoles = sysUserRoleService.getListByUserId(sysUser.getId());
        if(CollectionUtil.isEmpty(userRoles)) {
            return Collections.EMPTY_SET;
        }
        List<Long> roleIds = userRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
        List<SysRole> sysRoleMenuList = sysRoleService.getByIds(roleIds);
        return sysRoleMenuList.stream().map(SysRole::getRoleKey).collect(Collectors.toSet());
    }

}
